#include "GameManager.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include <fstream>


std::vector<Character*> g_characterTemplates;
GameManager::GameManager(Character* player)
    : player(player), currentMonsterIndex(0)
{
    std::srand(static_cast<unsigned int>(std::time(nullptr)));
    initializeLibraries();
    initializeCharacterTemplates();
}
GameManager::~GameManager() {
    delete player;
    for (auto tmpl : g_characterTemplates) delete tmpl;
}

//初始化
void GameManager::initializeLibraries() {

    // 从文件加载装备库
    equipmentLibrary = FileManager::loadEquipmentLibrary("data/equipment.json");

    // 从文件加载技能库
    skillLibrary = FileManager::loadSkillLibrary("data/skills.json");

    monsterLibrary = FileManager::loadMonsterLibrary("data/monsters.json");
    
}

void GameManager::initializeCharacterTemplates() {
    // 从 JSON 文件加载角色模板

    const std::string filename = "data/characters.json";
    std::ifstream file(filename);
    if (file.is_open()) {
        try {
            json j; file >> j;
            for (const auto& cj : j) {
                // 使用 Character::fromJson 创建带自定义属性的实例
                Character* tmpl = Character::fromJson(cj);
                if (tmpl) {
                    g_characterTemplates.push_back(tmpl);
                }
            }
        }
        catch (const std::exception& e) {
            std::cerr << "Error parsing characters.json: " << e.what() << std::endl;
        }
    }
    else {
        // 文件不存在，使用默认模板
        std::vector<json> defaults = {
            { {"type","Warrior"}, {"name","魔战士"}, {"info","魔化近战，较低生命，高攻击和魔力"},
              {"maxHealth",800}, {"attack",30}, {"defense",10}, {"maxMP",120} },
            { {"type","Warrior"}, {"name","狂战士"}, {"info","狂怒状态，高攻击，低防御"},
              {"maxHealth",900}, {"attack",35}, {"defense",8}, {"maxMP",100} },
            { {"type","Warrior"}, {"name","圣骑士"}, {"info","神圣守护者，高防御，具治疗力"},
              {"maxHealth",1200}, {"attack",20}, {"defense",25}, {"maxMP",80} },
            { {"type","Mage"}, {"name","火焰法师"}, {"info","掌控火焰，高爆发法术输出"},
              {"maxHealth",600}, {"attack",20}, {"defense",8}, {"maxMP",200} },
            { {"type","Mage"}, {"name","冰霜法师"}, {"info","冰冻对手，控制与输出兼备"},
              {"maxHealth",650}, {"attack",18}, {"defense",10}, {"maxMP",180} },
            { {"type","Mage"}, {"name","秘法法师"}, {"info","平衡型法师，生存与输出兼顾"},
              {"maxHealth",700}, {"attack",17}, {"defense",12}, {"maxMP",160} },
            { {"type","Archer"}, {"name","刺客"}, {"info","高爆发单体输出，生命与防御较低"},
              {"maxHealth",650}, {"attack",25}, {"defense",7}, {"maxMP",90} },
            { {"type","Archer"}, {"name","游侠"}, {"info","远程迅捷打手，灵活精准"},
              {"maxHealth",750}, {"attack",20}, {"defense",12}, {"maxMP",100} },
            { {"type","Archer"}, {"name","暗影舞者"}, {"info","潜行刺杀，20%几率暴击"},
              {"maxHealth",700}, {"attack",22}, {"defense",10}, {"maxMP",110} },
            { {"type","Archer"}, {"name","机械匠"}, {"info","机械辅助盗贼，拥有特殊陷阱技能"},
              {"maxHealth",800}, {"attack",18}, {"defense",15}, {"maxMP",120} }
        };
        json jdefaults = defaults;
        // 写入文件
        std::ofstream ofs(filename);
        ofs << jdefaults.dump(4);
        for (auto& cj : jdefaults) {
            if (Character* tmpl = Character::fromJson(cj)) {
                g_characterTemplates.push_back(tmpl);
            }
        }
    }
}

void GameManager::startGame() {
    std::cout << "===== 游戏开始 =====" << std::endl;
    std::cout << "角色: " << player->getName() << std::endl;
    std::cout << player->getInfo() << std::endl;

    generateMonster();

    while (player->getCurrentHealth() > 0) {
        battleTurn();



        // 检查怪物是否被击败
        if (!monsters[currentMonsterIndex].isAlive()) {
            player->defeatMonster();

            // 每击败10个怪物恢复状态
            if (player->getDefeatedCount() % 10 == 0) {
                player->RecoilState();

                std::cout << "\n\n================================\n";
                std::cout << "击败了" << player->getDefeatedCount() << "个怪物获得了治愈之泉！\n";
                std::cout << "HP和MP恢复了！\n";
                
                std::cout << "================================\n\n";
            }

            if (player->getDefeatedCount() % 5 == 0) {
                char saveChoice;
                while (true) {
                    std::cout << "\n你已经击败了 " << player->getDefeatedCount() << " 个怪物！是否要存档？(y/n): ";
                    std::cin >> saveChoice;

                    if (std::cin.fail()) {
                        std::cin.clear(); // 清除错误标志
                        std::string dummy;
                        std::getline(std::cin, dummy); // 丢弃无效输入
                        std::cout << "无效输入，请重新输入！" << std::endl;
                        continue;
                    }

                    if (saveChoice == 'y' || saveChoice == 'Y') {
                        saveGame(); // 自动存档（覆盖原存档）
                        break;
                    }
                    else if (saveChoice == 'n' || saveChoice == 'N') {
                        break;
                    }
                    else {
                        std::cin.clear();
                        std::string dummy;
                        std::getline(std::cin, dummy);
                        std::cout << "无效输入，请输入 y 或 n！" << std::endl;
                    }
                }
            }
            generateMonster();
        }
    }


    std::cout << "===== 游戏结束 =====" << std::endl;
}

bool GameManager::login() {
    std::string id, password;
    userList = FileManager::loadUsers("data/users.json");

    std::cout << "请输入ID: ";
    std::cin >> id;
    std::cout << "请输入密码: ";
    std::cin >> password;

    for (const auto& user : userList) {
        if (user.id == id && user.password == password) {
            currentUser = user;
            isLoggedIn = true;
            std::cout << (user.isAdmin ? "[管理员登录成功]" : "[用户登录成功]") << std::endl;
            return true;
        }
    }
    std::cout << "登录失败：ID或密码错误\n";
    return false;
}

void GameManager::saveGame(const std::string& slot) {
    if (!isLoggedIn) {
        std::cout << "请先登录再保存！" << std::endl;
        return;
    }

    // 使用当前用户的ID作为文件名
    if (FileManager::saveGameState(currentUser.id, *player, monsters, currentMonsterIndex)) {
        std::cout << "游戏已成功保存！" << std::endl;
    }
    else {
        std::cout << "保存游戏失败!" << std::endl;
    }
}

// 加载游戏
bool GameManager::loadGame(const std::string& slot) {
    if (!isLoggedIn) {
        std::cout << "请先登录再加载存档！" << std::endl;
        return false;
    }

    return FileManager::loadGameState(currentUser.id, player, monsters, currentMonsterIndex);
}

// 退出游戏
void GameManager::exitGame() {
    //saveGame("autosave");
    saveGame("");
    std::cout << "游戏已保存并退出!" << std::endl;
    exit(0);
}

void GameManager::showMainMenu() {
    if (!login()) return;

    int choice;
    while (true) {
        std::cout << "\n===== 主菜单 =====" << std::endl;
        std::cout << "1. 开始新游戏" << std::endl;
        std::cout << "2. 继续游戏" << std::endl;
        std::cout << "3. 退出游戏" << std::endl;
        if (currentUser.isAdmin)
            std::cout << "4. 管理资源库" << std::endl;
        std::cout << "请选择: ";
        std::cin >> choice;
        switch (choice) {
        case 1:
            player = selectCharacter();
            startGame(); return;
        case 2: 
            if (loadGame()) 
            { 
                std::cout << "游戏加载成功!\n"; startGame(); 
            }
            else 
            { 
                std::cout << "无存档, 开始新游戏!\n"; startGame();
            } return;
        
        case 3: exit(0);
        case 4: manageLibraries(); break;  // 进入库管理
        default: std::cout << "无效选择, 请重试!\n";
        }
    }
}

//战斗回合
void GameManager::battleTurn() {
    int choice;
    bool validChoice = false;
    Monster& currentMonster = monsters[currentMonsterIndex];

    while (!validChoice) {
        std::cout << "\n===== 战斗回合 =====" << std::endl;
        std::cout << player->getName() << " (HP: " << player->getCurrentHealth()
            << "/" << player->getMaxHealth() << " MP: " << player->getMP()
            << "/" << player->getMaxMP() << ")" << std::endl;
        std::cout << currentMonster.getName() << " (HP: " << currentMonster.getCurrentHealth()
            << "/" << currentMonster.getMaxHealth() << ")" << std::endl;

        std::cout << "\n选择行动:" << std::endl;
        std::cout << "0. 普通攻击" << std::endl;
        player->showSkills();
        
            
        std::cout << "请选择 (0-" << player->getSkills().size() << "): ";

        std::cin >> choice;

        if (std::cin.fail()) {
            std::cin.clear();
            std::string dummy;
            std::getline(std::cin, dummy);  // 丢弃这一行
            std::cout << "无效输入，请重新选择！" << std::endl;
            continue;
        }

        if (choice == 0) {
            player->Attack(currentMonster);
            validChoice = true;
        }
        else if (choice > 0 && choice <= player->getSkills().size()) {
            player->UseSkill(choice - 1, currentMonster);
            validChoice = true;
        }
        else {
            std::cout << "无效选择，请重新输入！" << std::endl;
        }
    }

    // 怪物反击（如果还活着）
    if (currentMonster.isAlive() && player->getCurrentHealth() > 0)
    {
        //TODO monsterAttack();

        std::cout << "\n" << currentMonster.getName() << "反击！" << std::endl;
        
        currentMonster.Attack(*player);
        player->OnTakeDamage(currentMonster.getAttack());
    }
}



#pragma region"随机抽取"
Equipment GameManager::getRandomEquipment(Difficulty difficulty) {
    if (equipmentLibrary.empty()) {
        // 处理错误情况
        return Equipment("", "", 0, 0, 0);
    }

    // 定义不同难度的索引范围
    int startIndex = 0;
    int endIndex = equipmentLibrary.size() - 1;

    // 根据难度设置范围
    switch (difficulty) {
    case Difficulty::EASY:
        endIndex = equipmentLibrary.size() * 0.2; // 前20%
        break;
    case Difficulty::MEDIUM:
        startIndex = equipmentLibrary.size() * 0.2;
        endIndex = equipmentLibrary.size() * 0.4; // 20%-40%
        break;
    case Difficulty::HARD:
        startIndex = equipmentLibrary.size() * 0.4;
        endIndex = equipmentLibrary.size() * 0.6; // 40%-60%
        break;
    case Difficulty::NIGHTMARE:
        startIndex = equipmentLibrary.size() * 0.6;
        endIndex = equipmentLibrary.size() * 0.8; // 60%-80%
        break;
    case Difficulty::HELL:
        startIndex = equipmentLibrary.size() * 0.8;
        endIndex = equipmentLibrary.size() - 1; // 后20%
        break;
    }

    // 确保索引有效
    startIndex = (startIndex >= 0) ? startIndex : 0;
    endIndex = (endIndex <= static_cast<int>(equipmentLibrary.size()) - 1) ?
        endIndex : static_cast<int>(equipmentLibrary.size()) - 1;

    // 使用现代C++随机数生成器
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distr(startIndex, endIndex);

    int index = distr(gen);
    return equipmentLibrary[index];
}

Skill GameManager::getRandomSkill(Difficulty difficulty) {
    if (skillLibrary.empty()) {
        // 处理错误情况
        return Skill("", "", 0, 0, 0);
    }

    // 定义不同难度的索引范围
    int startIndex = 0;
    int endIndex = skillLibrary.size() - 1;

    // 根据难度设置范围
    switch (difficulty) {
    case Difficulty::EASY:
        endIndex = skillLibrary.size() * 0.2; // 前20%
        break;
    case Difficulty::MEDIUM:
        startIndex = skillLibrary.size() * 0.2;
        endIndex = skillLibrary.size() * 0.4; // 20%-40%
        break;
    case Difficulty::HARD:
        startIndex = skillLibrary.size() * 0.4;
        endIndex = skillLibrary.size() * 0.6; // 40%-60%
        break;
    case Difficulty::NIGHTMARE:
        startIndex = skillLibrary.size() * 0.6;
        endIndex = skillLibrary.size() * 0.8; // 60%-80%
        break;
    case Difficulty::HELL:
        startIndex = skillLibrary.size() * 0.8;
        endIndex = skillLibrary.size() - 1; // 后20%
        break;
    }

    // 确保索引有效
    startIndex = (startIndex >= 0) ? startIndex : 0;
    endIndex = (endIndex <= static_cast<int>(skillLibrary.size()) - 1) ?
        endIndex : static_cast<int>(skillLibrary.size()) - 1;

    // 使用现代C++随机数生成器
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distr(startIndex, endIndex);

    int index = distr(gen);
    return skillLibrary[index];
}


// 按难度获取随机怪物
Monster GameManager::getRandomMonster(Difficulty difficulty) {
    if (monsterLibrary.empty()) {
        // 返回默认怪物
        return Monster("未知生物", "数据错误", 10, 5, 1);
    }

    size_t size = monsterLibrary.size();
    int startIndex = 0;
    int endIndex = static_cast<int>(size - 1);

    // 根据难度设置索引范围
    switch (difficulty) {
    case Difficulty::EASY:
        endIndex = static_cast<int>(size * 0.2);
        break;
    case Difficulty::MEDIUM:
        startIndex = static_cast<int>(size * 0.2);
        endIndex = static_cast<int>(size * 0.4);
        break;
    case Difficulty::HARD:
        startIndex = static_cast<int>(size * 0.4);
        endIndex = static_cast<int>(size * 0.6);
        break;
    case Difficulty::NIGHTMARE:
        startIndex = static_cast<int>(size * 0.6);
        endIndex = static_cast<int>(size * 0.8);
        break;
    case Difficulty::HELL:
        startIndex = static_cast<int>(size * 0.8);
        endIndex = static_cast<int>(size - 1);
        break;
    }

    // 确保索引有效
    startIndex = (startIndex >= 0) ? startIndex : 0;
    endIndex = (endIndex <= static_cast<int>(monsterLibrary.size()) - 1) ?
        endIndex : static_cast<int>(monsterLibrary.size()) - 1;
    // 使用现代随机数生成器
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distr(startIndex, endIndex);

    int index = distr(gen);
    return monsterLibrary[index];
}
#pragma endregion


void GameManager::generateMonster() {
    // 根据当前难度生成怪物
    Monster newMonster = getRandomMonster(currentDifficulty);

    // 随着玩家击败怪物数量增加，适当提升怪物属性
    int defeatCount = player->getDefeatedCount();
    if (defeatCount > 0) {
        // 简单的属性提升公式
        int healthBoost = defeatCount * 5;
        int attackBoost = defeatCount * 2;
        int defenseBoost = defeatCount * 1;

        newMonster.setMaxHealth(newMonster.getMaxHealth() + healthBoost);
        newMonster.setCurrentHealth(newMonster.getMaxHealth());
        newMonster.setAttack(newMonster.getAttack() + attackBoost);
        newMonster.setDefense(newMonster.getDefense() + defenseBoost);
    }

    monsters.push_back(newMonster);
    currentMonsterIndex = monsters.size() - 1;

    std::cout << "\n===== 遭遇了 " << newMonster.getName() << "! =====" << std::endl;
    std::cout << newMonster.getInfo() << std::endl;
}

#pragma region"库管理"
void GameManager::manageLibraries() {
    int libChoice;
    while (true) {
        std::cout << "\n--- 资源库管理 ---" << std::endl;
        std::cout << "1. 装备库" << std::endl;
        std::cout << "2. 技能库" << std::endl;
        std::cout << "3. 怪物库" << std::endl;
        std::cout << "4. 人物库" << std::endl;
        std::cout << "0. 返回主菜单" << std::endl;
        std::cout << "请选择库: "; std::cin >> libChoice;
        switch (libChoice) {
        case 1: manageEquipment(); break;
        case 2: manageSkills();    break;
        case 3: manageMonsters();  break;
        case 4: manageCharacters(); break;
        case 0: return;
        default: std::cout << "无效选择\n";
        }
    }
}

void GameManager::manageCharacters() {
    const std::string filename = "data/characters.json";
    int op;

    while (true) {
        std::cout << "\n-- 人物库管理 --" << std::endl;
        std::cout << "1. 显示所有人物" << std::endl;
        std::cout << "2. 根据名称查找" << std::endl;
        std::cout << "3. 添加" << std::endl;
        std::cout << "4. 删除" << std::endl;
        std::cout << "5. 修改" << std::endl;
        std::cout << "0. 返回" << std::endl;
        std::cout << "操作: ";
        std::cin >> op;
        if (op == 0) return;

        // 将内存中的模板同步到 JSON 数组
        json jchars = json::array();
        for (auto tmpl : g_characterTemplates) {
            jchars.push_back(tmpl->toJson());
        }

        switch (op) {
        case 1: {  // 显示所有人物
            for (size_t i = 0; i < g_characterTemplates.size(); ++i) {
                auto c = g_characterTemplates[i];
                std::cout << i << ": "
                    << c->getName() << " (" << c->getType() << ")  "
                    << "HP:" << c->getMaxHealth()
                    << " ATK:" << c->getTotalAttack()
                    << " DEF:" << c->getDefense()
                    << " MP:" << c->getMaxMP() << "\n"
                    << "    " << c->getInfo() << "\n";
            }
            break;
        }
        case 2: {  // 按名称查找
            std::string search;
            std::cout << "输入名称: ";
            std::cin >> search;
            bool found = false;
            for (auto c : g_characterTemplates) {
                if (c->getName() == search) {
                    std::cout << c->getName() << " - " << c->getInfo()
                        << " (HP:" << c->getMaxHealth()
                        << ", ATK:" << c->getTotalAttack()
                        << ", DEF:" << c->getDefense()
                        << ", MP:" << c->getMaxMP() << ")\n";
                    found = true;
                }
            }
            if (!found) {
                std::cout << "未找到名称为 '" << search << "' 的人物\n";
            }
            break;
        }
        case 3: {  // 添加新角色
            json nj;
            std::string type, name, info;
            int hp, atk, def, mp;

            std::cout << "类型: ";   std::cin >> type;
            std::cout << "名称: ";   std::cin >> name;
            std::cout << "描述: ";   std::cin.ignore(); std::getline(std::cin, info);
            std::cout << "HP, ATK, DEF, MP: "; std::cin >> hp >> atk >> def >> mp;

            nj["type"] = type;
            nj["name"] = name;
            nj["info"] = info;
            nj["maxHealth"] = hp;
            nj["attack"] = atk;
            nj["defense"] = def;
            nj["maxMP"] = mp;

            jchars.push_back(nj);
            g_characterTemplates.push_back(Character::fromJson(nj));
            
            break;
        }
        case 4: {  // 删除
            size_t idx;
            std::cout << "删除索引: "; std::cin >> idx;
            if (idx < g_characterTemplates.size()) {
                delete g_characterTemplates[idx];
                g_characterTemplates.erase(g_characterTemplates.begin() + idx);
                jchars.erase(jchars.begin() + idx);
            }
            break;
        }
        case 5: {  // 修改
            size_t idx;
            std::cout << "修改索引: "; std::cin >> idx;
            if (idx < jchars.size()) {
                auto& cj = jchars[idx];

                // 修改名称
                std::string newName;
                std::cout << "新名称 (" << cj["name"] << "): ";
                std::cin >> newName;
                cj["name"] = newName;

                // 修改描述
                std::string newInfo;
                std::cout << "新描述 (" << cj["info"] << "): ";
                std::cin.ignore();
                std::getline(std::cin, newInfo);
                cj["info"] = newInfo;

                // 修改属性 HP, ATK, DEF, MP
                int hp, atk, def, mp;
                std::cout << "HP(" << cj["maxHealth"]
                    << ") ATK(" << cj["attack"]
                    << ") DEF(" << cj["defense"]
                    << ") MP(" << cj["maxMP"]
                    << "): ";
                std::cin >> hp >> atk >> def >> mp;
                cj["maxHealth"] = hp;
                cj["attack"] = atk;
                cj["defense"] = def;
                cj["maxMP"] = mp;

                // 用更新后的 JSON 重建模板对象
                delete g_characterTemplates[idx];
                g_characterTemplates[idx] = Character::fromJson(cj);
            }
            break;
        }
        default:
            std::cout << "无效操作\n";
        }

        // 持久化回文件
        std::ofstream ofs(filename);
        ofs << jchars.dump(4);
    }
}

void GameManager::manageEquipment() {
    int op;
    while (true) {
        std::cout << "\n-- 装备库管理 --" << std::endl;
        std::cout << "1. 查找" << std::endl;
        std::cout << "2. 添加" << std::endl;
        std::cout << "3. 删除" << std::endl;
        std::cout << "4. 修改" << std::endl;
        std::cout << "0. 返回" << std::endl;
        std::cout << "操作: "; std::cin >> op;
        if (op == 0) return;
        switch (op) {
        case 1:
            
            std::cout << "1. 显示所有装备" << std::endl;
            std::cout << "2. 根据名称查找" << std::endl;
            int sub;
            std::cout << "选择: ";
            std::cin >> sub;
            if (sub == 1) {

                for (size_t i = 0; i < equipmentLibrary.size(); ++i)
                    std::cout <<std::setw(4)<< i << ": " << std::setw(10)<< equipmentLibrary[i].name << " (攻击+" << equipmentLibrary[i].attackBonus
                    << ", 防御+" << equipmentLibrary[i].defenseBonus
                    << ", 生命+" << equipmentLibrary[i].healthBonus << ")"
                    << " - " << equipmentLibrary[i].Info << "\n";


            }
            else if (sub == 2) {
                std::string search;
                std::cout << "输入名称: ";
                std::cin >> search;
                bool found = false;
                for (auto& mo : equipmentLibrary) {
                    if (mo.name == search) {
                        std::cout << mo.name << " - " << mo.Info << " (攻击+" << mo.attackBonus
                            << ", 防御+" << mo.defenseBonus
                            << ", 生命+" << mo.healthBonus << ")"
                            << " - " << mo.Info << "\n";

                        found = true;
                    }
                }
                if (!found) std::cout << "未找到名称为 '" << search << "' 的装备";

            }
            break;
        case 2: {
            std::string n, i; int a, d, h;
            std::cout << "名称: "; std::cin >> n;
            std::cout << "描述: "; std::cin >> i;
            std::cout << "攻击加成, 防御加成, 生命加成: "; std::cin >> a >> d >> h;
            equipmentLibrary.emplace_back(n, i, a, d, h);
            FileManager::saveEquipmentLibrary("data/equipment.json", equipmentLibrary);
            break;
        }
        case 3: {
            size_t idx; std::cout << "删除索引: "; std::cin >> idx;
            if (idx < equipmentLibrary.size()) equipmentLibrary.erase(equipmentLibrary.begin() + idx);
            FileManager::saveEquipmentLibrary("data/equipment.json", equipmentLibrary);
            break;
        }
        case 4: {
            size_t idx; std::cout << "修改索引: "; std::cin >> idx;
            if (idx < equipmentLibrary.size()) {
                std::cout << "新名称: "; std::cin >> equipmentLibrary[idx].name;
                std::cout << "新描述: "; std::cin >> equipmentLibrary[idx].Info;
                std::cout << "新攻击力 "; std::cin>> equipmentLibrary[idx].attackBonus;
                std::cout << "新防御力"; std::cin>> equipmentLibrary[idx].defenseBonus;
                std::cout << "新生命力"; std::cin>> equipmentLibrary[idx].healthBonus;
                FileManager::saveEquipmentLibrary("data/equipment.json", equipmentLibrary);
            }
            break;
        }
        }
    }
}

void GameManager::manageSkills() {
    int op;
    while (true) {
        std::cout << "\n-- 技能库管理 --" << std::endl;
        std::cout << "1. 查找" << std::endl;
        std::cout << "2. 添加" << std::endl;
        std::cout << "3. 删除" << std::endl;
        std::cout << "4. 修改" << std::endl;
        std::cout << "0. 返回" << std::endl;
        std::cout << "操作: "; std::cin >> op;
        if (op == 0) return;
        switch (op) {
        case 1:
            std::cout << "1. 显示所有技能" << std::endl;
            std::cout << "2. 根据名称查找" << std::endl;
            int sub;
            std::cout << "选择: ";
            std::cin >> sub;
            if (sub == 1) {

                for (size_t i = 0; i < skillLibrary.size(); ++i)
                    std::cout << i << ": " << skillLibrary[i].name <<  " (消耗MP: " << skillLibrary[i].cost << ")"
                    << " - " << skillLibrary[i].Info<<"\n";
                    

            }
            else if (sub == 2) {
                std::string search;
                std::cout << "输入名称: ";
                std::cin >> search;
                bool found = false;
                for (auto& mo : skillLibrary) {
                    if (mo.name == search) {
                        std::cout << mo.name << " - " << mo.Info << " (消耗MP: " << mo.cost << ")"
                            << " - " << mo.Info << "\n";

                        found = true;
                    }
                }
                if (!found) std::cout << "未找到名称为 '" << search << "' 的技能";

            }
            break;
        case 2: {
            std::string n, i; int cost, at, df;
            std::cout << "名称: "; std::cin >> n;
            std::cout << "描述: "; std::cin >> i;
            std::cout << "消耗MP, 攻击, 防御: "; std::cin >> cost >> at >> df;
            skillLibrary.emplace_back(n, i, cost, at, df);
            FileManager::saveSkillLibrary("data/skills.json", skillLibrary);
            break;
        }
        case 3: {
            size_t idx; std::cout << "删除索引: "; std::cin >> idx;
            if (idx < skillLibrary.size()) skillLibrary.erase(skillLibrary.begin() + idx);
            FileManager::saveSkillLibrary("data/skills.json", skillLibrary);
            break;
        }
        case 4: {
            size_t idx; std::cout << "修改索引: "; std::cin >> idx;
            if (idx < skillLibrary.size()) {
                std::cout << "新名称: "; std::cin >> skillLibrary[idx].name;
                std::cout << "新描述: "; std::cin >> skillLibrary[idx].Info;
                std::cout << "新攻击力: "; std::cin >> skillLibrary[idx].attack;
                std::cout << "新消耗量: "; std::cin >> skillLibrary[idx].cost;
                std::cout << "新治疗量: "; std::cin >> skillLibrary[idx].hp;
                FileManager::saveSkillLibrary("data/skills.json", skillLibrary);
            }
            break;
        }
        }
    }
}

void GameManager::manageMonsters() {
    int op;
    while (true) {
        std::cout << "\n-- 怪物库管理 --" << std::endl;
        std::cout << "1. 查找" << std::endl;
        std::cout << "2. 添加" << std::endl;
        std::cout << "3. 删除" << std::endl;
        std::cout << "4. 修改" << std::endl;
        std::cout << "0. 返回" << std::endl;
        std::cout << "操作: "; std::cin >> op;
        if (op == 0) return;
        switch (op) {
        case 1:
            std::cout << "1. 显示所有怪物" << std::endl;
            std::cout << "2. 根据名称查找" << std::endl;
            int sub;
            std::cout << "选择: ";
            std::cin >> sub;
            if (sub == 1) {
                for (auto& mo : monsterLibrary)
                    std::cout << mo.getName() << " - " << mo.getInfo() << " (HP " << mo.getMaxHealth() << ", ATK " << mo.getAttack() << ")"<<std::endl;
                  
            }
            else if (sub == 2) {
                std::string search;
                std::cout << "输入名称: ";
                std::cin >> search;
                bool found = false;
                for (auto& mo : monsterLibrary) {
                    if (mo.getName() == search) {
                        std::cout << mo.getName() << " - " << mo.getInfo() << " (HP " << mo.getMaxHealth() << ", ATK " << mo.getAttack() << ")"<<std::endl;
                           
                            found = true;
                    }
                }
                if (!found) std::cout << "未找到名称为 '" << search << "' 的怪物";
                   
            }
            break;
        case 2: {
            std::string n, i; int h, at, df;
            std::cout << "名称: "; std::cin >> n;
            std::cout << "描述: "; std::cin >> i;
            std::cout << "生命, 攻击, 防御: "; std::cin >> h >> at >> df;
            monsterLibrary.emplace_back(n, i, h, at, df);
            break;
        }
        case 3: {
            size_t idx; std::cout << "删除索引: "; std::cin >> idx;
            if (idx < monsterLibrary.size()) monsterLibrary.erase(monsterLibrary.begin() + idx);
            break;
        }
        case 4: {
            size_t idx; std::cout << "修改索引: "; std::cin >> idx;
            if (idx < monsterLibrary.size()) {
                std::string newName, newInfo;
                std::cout << "新名称: ";
                std::cin >> newName;
                std::cout << "新描述: ";
                std::cin >> newInfo;
                monsterLibrary[idx].setName(newName);
                monsterLibrary[idx].setInfo(newInfo);
            }
            break;
        }
        }
    }
}

#pragma endregion

Character* GameManager::selectCharacter() {
    std::cout << "===== 选择职业 =====" << std::endl;
    for (int i = 0; i < g_characterTemplates.size(); ++i) {
        auto tmpl = g_characterTemplates[i];
        std::cout << i + 1 << ". " << tmpl->getName()
            << "-"<<"职业" << tmpl->getType()
            << " (HP:" << tmpl->getMaxHealth()
            << ", ATK:" << tmpl->getTotalAttack()
            << ", DEF:" << tmpl->getDefense()
            << ", MP:" << tmpl->getMaxMP() << ") - "
            /*<< tmpl->getInfo() */
            << std::endl;
    }
    int choice = 0;
    while (choice < 1 || choice > g_characterTemplates.size()) {
        std::cout << "请输入(1-" << g_characterTemplates.size() << "): ";
        std::cin >> choice;
    }
    Character* newCharacter = g_characterTemplates[choice - 1]->clone();

   
   

    return newCharacter;
}

